package com.klod.data.repository

import com.klod.data.bean.BannerDetailBean

import com.klod.data.mapping.BannersTable
import com.klod.data.mapping.daoToModel

import com.klod.ext.suspendTransaction
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll
import org.koin.core.annotation.Single

@Single
class BannerRepository : BannerRepositoryI {
    override suspend fun findAllBanners(): MutableList<BannerDetailBean> = suspendTransaction {
//        BannersDAO.all().map(::daoToModel).toMutableList()
        BannersTable.selectAll().map(::daoToModel).toMutableList()
    }

    override suspend fun findBannerById(bId: Int): BannerDetailBean? = suspendTransaction {
//        BannersDAO.find { (BannersTable.bId eq bId) }
//            .limit(1)
//            .map(::daoToModel)
//            .firstOrNull()
        BannersTable.selectAll()
            .where { BannersTable.bId eq bId }
            .map(::daoToModel)
            .singleOrNull()
    }

    override suspend fun addBanner(task: BannerDetailBean): Int = suspendTransaction {
//        BannersDAO.new {
////            bId = task.bId
//            imgUrl = task.imageUrl
//            content = task.content
//        }.let(::daoToModel )

//        BannersTable.insert {
//
//        } get BannersTable.bId
        BannersTable.insert {
            it[imgUrl] = task.imageUrl
            it[content] = task.content
        }[BannersTable.bId]
//
    }

    override suspend fun removeBanner(bId: Int): Boolean = suspendTransaction {
        BannersTable.deleteWhere {
            (BannersTable.bId eq bId)
        } == 1
    }
}